<template>
  <div v-if="isShow" class="promotional-video">
    <div class="video-action">
      <b-form-checkbox
        v-model="week"
        name="checkbox-1"
        value="1"
        unchecked-value="0"
      >最近一周不显示</b-form-checkbox>
      <b-badge @click="handleClose" variant="dark">关闭</b-badge>
    </div>
    <Video :url="videoUrl" ref="video" :options="{autoplay: true, muted: true}" />
  </div>
</template>

<script>
import Video from './video.vue'

export default {
  components: {
    Video
  },

  data () {
    return {
      isShow: false,
      videoUrl: '/mock/videos/p5l3ki3mjtghm.mp4',
      week: '0'
    }
  },

  mounted () {
    let value = localStorage.getItem('promotional-video')
    if (!value) {
      this.isShow = true
    } else {
      try {
        value = JSON.parse(value)
        let week = value.week || '0'
        let time = parseInt(value.time) || 0
        let isShow = true
        if (week === '1') {
          time += 7 * 24 * 60 ^0 * 1000
        } else {
          time += 1 * 24 * 60 ^0 * 1000
        }
        if (time < Date.now()) {
          isShow = false
        }
        this.isShow = isShow
      } catch (e) {
        this.isShow = true
      }
    }
    if (this.isShow) {
      this.$nextTick(() => {
        this.playVideo()
      })
    }
  },

  methods: {
    // 播放视频
    playVideo () {
      let data = {
        url: '/mock/videos/p5l3ki3mjtghm.mp4'
      }
      this.videoUrl = data.url
      let videoView = this.$refs.video
      videoView.play()
      videoView.videoPlayer.on('ended', () => {
        this.isShow = false
      })
    },
    // 关闭
    handleClose (week) {
      this.isShow = false
      week = week || this.week
      localStorage.setItem('promotional-video', JSON.stringify({
        week,
        time: Date.now()
      }))
    }
  }
}
</script>

<style lang="less" scoped>
.promotional-video {
  height: 64vh;
  .view-player {
    height: calc(100% - 24px);
  }
  .video-action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .custom-control {
      display: flex;
      align-items: center;
      user-select: none;
    }
    /deep/ .custom-control-input {
      width: auto;
      height: auto;
    }
    /deep/ .custom-control-label {
      color: #666;
      font-size: 12px;
      &:before,&:after {
        top: 0.14rem;
      }
    }
    .badge {
      margin-left: 12px;
      cursor: pointer;
    }
  }
}
</style>